package com.cloud.class05.test;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

// 运用信号量实现实现4个车位8个人有序停车
public class SemaphoreExample {
    public static void main(String[] args) {
        //表示4个车位这就是信号量
        Semaphore semaphore = new Semaphore(4);
        //创建一个固定大小的线程池
//        jdk所提供创建线程池的四种方法
//        固定的线程池 、可变的线程池 、单线程池 、定时线程池
        ExecutorService executorService = Executors.newFixedThreadPool(8);
//        向线程池中提交8个任务
        for (int i = 0; i < 8; i++) {
            executorService.submit(new Task(semaphore, i));
        }
//        关闭线程池
        executorService.shutdown();

    }


    static class Task implements Runnable {
        private Semaphore semaphore;
        private int id;
        public Task(Semaphore semaphore, int id) {
            this.semaphore = semaphore;
            this.id = id;
        }
        @Override
        public void run() {
            try {
                // 获取信号量
                semaphore.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + "进来了一辆汽车来停车");
                Thread.sleep(2000);
                System.out.println("线程" + Thread.currentThread().getName() + "一辆汽车走了，下一辆可以进来了");
//                释放信号量
                semaphore.release();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


        }

    }
}
